package cn.yuanqiao.archive.danganzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqFolderMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqItemMapper;
import cn.yuanqiao.archive.appManager.mapper.TenantYqdaMapper;
import cn.yuanqiao.archive.danganzhengli.domain.HandOverDa;
import cn.yuanqiao.archive.danganzhengli.mapper.HandOverDaMapper;
import cn.yuanqiao.archive.danganzhengli.service.IDanganzhengliService;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zjj
 * @date 2023/7/5
 */
@Service
public class DanganzhengliServiceImpl implements IDanganzhengliService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqItemMapper itemMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private HandOverDaMapper handOverDaMapper;
    @Autowired
    private TenantItemFolderMapper itemFolderMapper;

    @Override
    @Transactional
    public int tuihui(Long categoryId,Long [] ids) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        Map<String,String> column = new HashMap<>();
        column.put("IS_INDEX","1");
        //处理项目层
        if(category.getType() == 3) {
            for(Long id:ids){
                HandOverDa handOverDa = new HandOverDa();
                handOverDa.setDaId(id);
                handOverDa.setDaType(3);
                int daCount = handOverDaMapper.selectCount(handOverDa);
                if(daCount>0){
                    throw new ServiceException("选择的档案有在移交单中的数据，请先在移交单中删除，再退回！");
                }

                Map<String,Object> data= itemMapper.getItemById("JS_TYPE",id,category.getItemTableName());
                column.put("STATE",getStateByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                //修改项目
                TenantYqItem item = new TenantYqItem();
                item.setColNames(column);
                item.setItemId(id);
                itemMapper.updateItem(item); //主表
                item.setTableName(category.getItemTableName());
                itemMapper.updateItemDisperse(item);  //分表

                //修改卷
                Long [] itemId = new Long[]{id};
                Long [] folderIds = folderMapper.getFolderIdsByItemIds(itemId,category.getFolderTableName(),new TenantItemFolder().getTableName());
                if(folderIds !=null && folderIds.length>0){
                    for(Long folderId:folderIds){

                        Map<String,Object> boxState = folderMapper.getYqFolderById("BOXSTATE",folderId,category.getFolderTableName());
                        if(boxState != null && "1".equals(boxState.get("BOXSTATE"))){
                            throw new ServiceException("选择的档案已装盒，不能退回！");
                        }

                        TenantYqFolder yqFolder = new TenantYqFolder();
                        yqFolder.setColNames(column);
                        yqFolder.setFolderId(folderId);
                        folderMapper.updateYqFolder(yqFolder);
                        yqFolder.setTableName(category.getFolderTableName());
                        folderMapper.updateYqFolderDisperse(yqFolder);
                    }

                    //修改件
                    Long [] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds,category.getFileTableName(),new TenantYqdaFolder().getTableName());
                    if(daIds !=null && daIds.length>0){
                        for(Long daId:daIds){
                            TenantYqda yqda = new TenantYqda();
                            yqda.setColNames(column);
                            yqda.setDaId(daId);
                            yqdaMapper.updateYqda(yqda);
                            yqda.setTableName(category.getFileTableName());
                            yqdaMapper.updateYqdaDisperse(yqda);
                        }
                    }
                }

            }
        }else if(category.getType() == 1){
            //处理组卷
            for(Long folderId:ids){
                HandOverDa handOverDa = new HandOverDa();
                handOverDa.setDaId(folderId);
                handOverDa.setDaType(1);
                int daCount = handOverDaMapper.selectCount(handOverDa);
                if(daCount>0){
                    throw new ServiceException("选择的档案有在移交单中的数据，请先在移交单中删除，再退回！");
                }
                Map<String,Object> boxState = folderMapper.getYqFolderById("BOXSTATE",folderId,category.getFolderTableName());
                if(boxState != null && "1".equals(boxState.get("BOXSTATE"))){
                    throw new ServiceException("选择的档案已装盒，不能退回！");
                }
                Map<String,Object> data= folderMapper.getYqFolderById("JS_TYPE",folderId,category.getFolderTableName());
                column.put("STATE",getStateByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                //修改卷
                TenantYqFolder yqFolder = new TenantYqFolder();
                yqFolder.setColNames(column);
                yqFolder.setFolderId(folderId);
                folderMapper.updateYqFolder(yqFolder);
                yqFolder.setTableName(category.getFolderTableName());
                folderMapper.updateYqFolderDisperse(yqFolder);

                //修改件
                Long [] folderIds = new Long[]{folderId};
                Long [] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds,category.getFileTableName(),new TenantYqdaFolder().getTableName());
                if(daIds !=null && daIds.length>0){
                    for(Long daId:daIds){
                        TenantYqda yqda = new TenantYqda();
                        yqda.setColNames(column);
                        yqda.setDaId(daId);
                        yqdaMapper.updateYqda(yqda);
                        yqda.setTableName(category.getFileTableName());
                        yqdaMapper.updateYqdaDisperse(yqda);
                    }
                }
            }
        } else if(category.getType() == 0){
            //处理组件
            for(Long daId:ids){
                HandOverDa handOverDa = new HandOverDa();
                handOverDa.setDaId(daId);
                handOverDa.setDaType(0);
                int daCount = handOverDaMapper.selectCount(handOverDa);
                if(daCount>0){
                    throw new ServiceException("选择的档案有在移交单中的数据，请先在移交单中删除，再退回！");
                }
                Map<String,Object> boxState = yqdaMapper.getYqdaById("BOXSTATE",daId,category.getFileTableName());
                if(boxState != null && "1".equals(boxState.get("BOXSTATE"))){
                    throw new ServiceException("选择的档案已装盒，不能退回！");
                }

                Map<String,Object> data = yqdaMapper.getYqdaById("JS_TYPE",daId,category.getFileTableName());
                column.put("STATE",getStateByJsType(Integer.valueOf(data.get("JS_TYPE").toString())));
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(column);
                yqda.setDaId(daId);
                yqdaMapper.updateYqda(yqda);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.updateYqdaDisperse(yqda);
            }
        }

        return 1;
    }

    @Override
    public void tuihuiAnJuan(Long categoryId, Long[] folderIds) {
        TenantCategory category = new TenantCategory();
        category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
        Map<String,String> column = new HashMap<>();
        column.put("IS_INDEX","1");
        column.put("STATE","10");  //待归档
        List<Map<String,Object>> itemList = itemFolderMapper.selectItemList(folderIds,new TenantItemFolder().getTableName());
        //修改卷
        for(Long folderId:folderIds){
            Map<String,Object> boxState = folderMapper.getYqFolderById("BOXSTATE",folderId,category.getFolderTableName());
            if(boxState != null && "1".equals(boxState.get("BOXSTATE"))){
                throw new ServiceException("选择的档案已装盒，不能退回！");
            }

            TenantYqFolder yqFolder = new TenantYqFolder();
            yqFolder.setColNames(column);
            yqFolder.setFolderId(folderId);
            folderMapper.updateYqFolder(yqFolder);
            yqFolder.setTableName(category.getFolderTableName());
            folderMapper.updateYqFolderDisperse(yqFolder);
        }

        //修改件
        Long [] daIds = yqdaMapper.getDaIdsByFolderIds(folderIds,category.getFileTableName(),new TenantYqdaFolder().getTableName());
        for(Long daId:daIds){
            TenantYqda yqda = new TenantYqda();
            yqda.setColNames(column);
            yqda.setDaId(daId);
            yqdaMapper.updateYqda(yqda);
            yqda.setTableName(category.getFileTableName());
            yqdaMapper.updateYqdaDisperse(yqda);
        }

        //更新项目层归档卷数 和 件数
        for(Map<String,Object> item:itemList){
            //归档案卷数量
            Integer numJuan = itemFolderMapper.getFolderNumByItemIdYGD(category.getFolderTableName(), SecurityUtils.getTenantCode(), String.valueOf(item.get("ITEM_ID")));
            //归档文件数量
            Integer numJian = itemFolderMapper.getDaNumByItemIdYGD(category.getFileTableName(),category.getFolderTableName(),SecurityUtils.getTenantCode(), String.valueOf(item.get("ITEM_ID")));
            TenantYqItem yqItem = new TenantYqItem();
            Map<String,String> data = new HashMap<>();
            data.put("GDAJSL", String.valueOf(numJuan));
            data.put("GDWJSL", String.valueOf(numJian));
            yqItem.setColNames(data);
            yqItem.setItemId(Long.valueOf(String.valueOf(item.get("ITEM_ID"))));
            itemMapper.updateItem(yqItem);
            yqItem.setTableName(category.getItemTableName());
            itemMapper.updateItemDisperse(yqItem);
        }
    }

    /**
     * 判断退回的状态
     * @param jsType
     * @return
     */
    private String getStateByJsType(int jsType){
        /*State
        1:预归档-未接收
        2:预归档-已接收
        3:数字化成果未接收
        4:归档审批中
        5:已归档
        6:移交审批中   --没用
        7:已移交      --没用
        8：已销毁
        9：预归档流程中
        10：预归档已完成
        11 档案征集
        12 接收管理
        13 移交包接收
        999:文书资料库*/
         /*jsType
         0:离线接收(又:手工著录)1:在线接收
        2:档案接收(数字化成果目录)
        3:档案征集4:接收管理
        5:电子档案接收(退回:4)
        6:数据库接收(退回:4)
        7:档案管理-目录导入(退回:4)*/
        if (jsType == 0 || jsType == 1) {
            return "2";
        } else if (jsType == 2) {
            return "3";
        } else if (jsType == 3) {
            return "11";
        }else if(jsType == 4){
            return "12";
        }else if (jsType == 5 || jsType == 6) {
            return "12";
        }else if(jsType == 7){
            return "12";
        }else if (jsType == 9 || jsType == 10) {
            return "10";
        }  else {
            throw new ServiceException("未查询到JS_TYPE");
        }
    }
}
